package com.dy.project.domain;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;

import java.util.Date;
import java.util.List;

/**
 * 用于返回Ajax请求的JSON类
 */
public class AjaxResult extends JSONObject {
    /**
     * 接口调用成功返回常量
     */
    public static final int OK = 200;
    /**
     * 接口调用返回信息
     */
    private String msg;

    /**
     * 结果总数
     */
    private int count;

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    /**
     * 创建一个JSON对象并赋值状态码和信息
     */
    public AjaxResult ok(){
        return this.setCodeAndMsg(OK,"调用成功。");
    }

    public AjaxResult ok(String msg){
        return this.setCodeAndMsg(OK,msg);
    }

    public AjaxResult ok(String msg,Object data){
        this.setData(data);
        return this.setCodeAndMsg(OK,msg);
    }

    public AjaxResult ok(Object data){
        this.setData(data);
        return this.setCodeAndMsg(OK,"调用成功。");
    }

    public AjaxResult err(int code){
        return this.setCodeAndMsg(code,"发生错误。");
    }

    public AjaxResult err(int code,String msg){
        return this.setCodeAndMsg(code,msg);
    }

    public AjaxResult setCodeAndMsg(int code,String msg){
        super.put("timestamp",new Date().getTime());
        super.put("code",code);
        super.put("msg",msg);
        return this;
    }

    /**
     * 赋值数据
     */
    public void setData(Object data){
        if(data instanceof PageInfo){
            PageInfo pageInfo = (PageInfo) data;
            super.put("count",pageInfo.getTotal());
            super.put("data",pageInfo.getList());
        }else if(data instanceof List){
            super.put("count",((List) data).size());
            super.put("data",data);
        }else{
            super.put("count",1);
            super.put("data",data);
        }
    }

    public void setError(String errMsg){
        super.put("error",errMsg);
    }
}
